
package com.bear.cmcc.NetTestHTTP.ui.activity;

import com.bear.cmcc.NetTestHTTP.NetworkTestApp;
import com.bear.cmcc.NetTestHTTP.R;
import com.bear.cmcc.NetTestHTTP.SplashScreenActivity;
import com.bear.cmcc.NetTestHTTP.component.MenuBean;
import com.bear.cmcc.NetTestHTTP.constant.LocationConstant;
import com.bear.cmcc.NetTestHTTP.constant.MyCommonConstant;
import com.bear.cmcc.NetTestHTTP.ui.view.MenuLayout;
import com.bear.cmcc.NetTestHTTP.ui.view.MenuLayout.OnItemMenuClickListener;
import com.bear.cmcc.NetTestHTTP.ui.view.UpdateCellDBView;
import com.bear.cmcc.NetTestHTTP.util.MyCommonUtil;
import com.bear.cmcc.NetTestHTTP.util.NetTestDBUtil;
import com.bear.cmcc.NetTestHTTP.util.SetUtil;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 * 视图基类 AbstractActivity
 * 
 * @author Administrator
 */

public class AbstractActivity extends Activity {

    private ProgressBar proBar;

    private View oldItemView;

    private int bottomBarIndx;

    private LocationAndNetReceiver locationAndNetReceiver = new LocationAndNetReceiver();

    private APPExitReceiver exitReceiver = new APPExitReceiver();

    private UpdateCellDBView upCellDBView;// 导入小区数据库界面

    private MenuLayout menuView;// 弹出的系统菜单

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setBackGround(R.drawable.backgroud);
        super.setContentView(R.layout.activity_abstract);
        proBar = (ProgressBar) findViewById(R.id.proBar);
        upCellDBView = (UpdateCellDBView) findViewById(R.id.abstract_upCellDBView);
        menuView = (MenuLayout) findViewById(R.id.abstract_menuLayout);
        initializeListener();
        // 初化弹出的系统菜单
        initMenu();
    }

    @Override
    protected void onDestroy() {
        upCellDBView.onDestroy();
        if (locationAndNetReceiver != null) {
            unregisterReceiver(locationAndNetReceiver);
        }
        if (exitReceiver != null) {
            unregisterReceiver(exitReceiver);
        }
        super.onDestroy();
    }

    protected void CloseServerDispose() {

    }

    /**
     * 系统菜单
     */
    private void initMenu() {
        menuView.refresh(MyCommonUtil.getMenuList(this));
        menuView.setOnItemMenuClickListener(new OnItemMenuClickListener() {

            @Override
            public void onItemClick(MenuBean b) {
                switch (b.getId()) {
                    case MyCommonConstant.Menu_options.MENU_REFRESH:
                        // 刷新
                        refresh();
                        break;
                    case MyCommonConstant.Menu_options.MENU_KILL_SERVICE:
                        // 关闭服务
                        MyCommonUtil.closeAllService(AbstractActivity.this);
                        MyCommonUtil.showMessage(AbstractActivity.this,
                                R.string.kill_service_success);
                        CloseServerDispose();
                        break;
                    case MyCommonConstant.Menu_options.MENU_SET:
                        // 设置
                        startActivity(new Intent(AbstractActivity.this, SettingActivity.class));
                        break;
                    case MyCommonConstant.Menu_options.MENU_CELLDB:
                        // 插入小区数据库
                        if (MyCommonUtil.isNetworkAviable(AbstractActivity.this)) {
                            SetUtil.importVillageInfo(AbstractActivity.this);
                            upCellDBView.setVisibility(View.VISIBLE);
                        } else {
                            MyCommonUtil.showMessage(AbstractActivity.this, R.string.no_network);
                        }
                        break;
                    case MyCommonConstant.Menu_options.MENU_ABOUT:
                        // 关于
                        startActivity(new Intent(AbstractActivity.this, AboutActivity.class));
                        break;
                    case MyCommonConstant.Menu_options.MENU_EXIT:
                        // 退出
                        MyCommonUtil.exit(AbstractActivity.this);
                        break;
                    case MyCommonConstant.Menu_options.MENU_EXPORT_DATA:
                        // 导出测试数据
                        NetTestDBUtil.exportTestDBInfo(AbstractActivity.this);
                        break;
                    case MyCommonConstant.Menu_options.MENU_IMPORT_DATA:
                        // 导入测试数据
                        NetTestDBUtil.importTestDBInfo(AbstractActivity.this);
                        break;
                    case MyCommonConstant.Menu_options.MENU_LOGOUT:
                        SetUtil.setLoginInfoLogout(AbstractActivity.this);
                        MyCommonUtil.showLoginDialog(AbstractActivity.this);
                        break;
                }
            }

        });

    }

    /**
     * 初始化广播
     */
    private void initializeListener() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(LocationConstant.ACTION_LOCATION_BROADCASE);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        this.registerReceiver(locationAndNetReceiver, filter);

        // 注册应用退出广播
        IntentFilter extFilter = new IntentFilter();
        extFilter.addAction(MyCommonConstant.PrivateActionName.APP_EXIT_FINISH);
        registerReceiver(exitReceiver, extFilter);
    }

    public void SetTopBarVisible(Boolean bool) {
        RelativeLayout layout = (RelativeLayout) findViewById(R.id.layout_top);

        if (bool == true) {
            layout.setVisibility(View.VISIBLE);
        } else {
            layout.setVisibility(View.INVISIBLE);
        }
    }

    public void SetBottomBarVisible(Boolean bool) {
        LinearLayout layout = (LinearLayout) findViewById(R.id.layout_guide);
        RelativeLayout rlayout = (RelativeLayout) findViewById(R.id.r_layout_content);

        if (bool == true) {

        } else {
            rlayout.removeView(layout);
        }
    }

    public void choseBottomItemIndex(int index) {
        bottomBarIndx = index;
        LinearLayout lBar = (LinearLayout) findViewById(R.id.layout_guide);
        if (lBar != null) {
            View view = lBar.getChildAt(bottomBarIndx);
            if (null != oldItemView) {
                oldItemView.setBackgroundResource(R.drawable.bg_bottom_item_press);
            }
            if (view != null) {
                view.setBackgroundResource(R.drawable.bg_bottom_item_s);
            }

            this.oldItemView = view;
        }
    }

    protected void showNoteDialog(String msg) {
        AlertDialog.Builder normalDia = new AlertDialog.Builder(AbstractActivity.this);
        normalDia.setIcon(R.drawable.ic_launcher);
        normalDia.setTitle(R.string.dlg_note_title);
        normalDia.setMessage(msg);

        normalDia.setNeutralButton(R.string.dlg_note_btn_confirm,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });

        normalDia.setCancelable(true);

        normalDia.create().show();
    }

    protected void responseForCountry(boolean showLogin) {
        choseBottomItemIndex(MyCommonConstant.COUNTRY_ACTIVITY_INDEX);

        // Intent intent = new Intent();
        // intent.setClass(AbstractActivity.this, NationalInfoActivity.class);
        // intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        // startActivity(intent);

        MyCommonUtil.startFjActivity(AbstractActivity.this);
        overridePendingTransition(0, 0);

    }

    protected void responseForCityTop() {
        choseBottomItemIndex(MyCommonConstant.TOP_ACTIVITY_CITY_INDEX);
        {
            Intent intent = new Intent();
            intent.setClass(AbstractActivity.this, CityTopActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            overridePendingTransition(0, 0);
        }
    }

    // protected void responseForSubscrible() {
    // choseBottomItemIndex(2);
    // {
    // Intent intent = new Intent();
    // intent.setClass(AbstractActivity.this, InfoSubscribleActivity.class);
    // intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    // startActivity(intent);
    // overridePendingTransition(0, 0);
    // }
    // }

    protected void responseForTestTool() {
        choseBottomItemIndex(MyCommonConstant.TEST_ACTIVITY_INDEX);
        {
            Intent intent = new Intent();
            intent.setClass(AbstractActivity.this, NetTestActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            overridePendingTransition(0, 0);
        }
    }

    private void CreateBottomCountry() {
        LinearLayout lBar = (LinearLayout) findViewById(R.id.layout_guide);

        View item;
        item = View.inflate(getApplicationContext(), R.layout.layout_bottom_item, null);
        item.setBackgroundResource(R.drawable.btn_press_bg);
        TextView tv = (TextView) item.findViewById(R.id.list_item_textview);
        tv.setText(R.string.bottom_country);

        ImageView iv = (ImageView) item.findViewById(R.id.list_item_icon);
        iv.setImageDrawable(getResources().getDrawable(R.drawable.bottom_icon_nation));

        LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT,
                1);

        lBar.addView(item, params);
        item.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                responseForCountry(false);
            }
        });

    }

    private void CreateBottomCityTop() {
        LinearLayout lBar = (LinearLayout) findViewById(R.id.layout_guide);

        View item;
        item = View.inflate(getApplicationContext(), R.layout.layout_bottom_item, null);
        item.setBackgroundResource(R.drawable.btn_press_bg);
        TextView tv = (TextView) item.findViewById(R.id.list_item_textview);
        tv.setText(R.string.bottom_city_top_new);

        ImageView iv = (ImageView) item.findViewById(R.id.list_item_icon);
        iv.setImageDrawable(getResources().getDrawable(R.drawable.bottom_icon_citytop));

        LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT,
                1);

        lBar.addView(item, params);
        item.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                responseForCityTop();
            }
        });

    }

    // private void CreateBottomSubscrible() {
    // LinearLayout lBar = (LinearLayout) findViewById(R.id.layout_guide);
    //
    // View item;
    // item = View.inflate(getApplicationContext(), R.layout.layout_bottom_item,
    // null);
    // item.setBackgroundResource(R.drawable.btn_press_bg);
    // TextView tv = (TextView) item.findViewById(R.id.list_item_textview);
    // tv.setText(R.string.bottom_subscrible);
    //
    // ImageView iv = (ImageView) item.findViewById(R.id.list_item_icon);
    // iv.setImageDrawable(getResources().getDrawable(R.drawable.bottom_icon_subscrible));
    //
    // LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT,
    // LayoutParams.FILL_PARENT,
    // 1);
    //
    // lBar.addView(item, params);
    // item.setOnClickListener(new View.OnClickListener() {
    //
    // @Override
    // public void onClick(View v) {
    // responseForSubscrible();
    // }
    // });
    //
    // }

    private void CreateBottomTestTool() {
        LinearLayout lBar = (LinearLayout) findViewById(R.id.layout_guide);

        View item;
        item = View.inflate(getApplicationContext(), R.layout.layout_bottom_item, null);
        item.setBackgroundResource(R.drawable.btn_press_bg);
        TextView tv = (TextView) item.findViewById(R.id.list_item_textview);
        tv.setText(R.string.bottom_test_tool);

        ImageView iv = (ImageView) item.findViewById(R.id.list_item_icon);
        iv.setImageDrawable(getResources().getDrawable(R.drawable.bottom_icon_test_tool));

        LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT,
                1);

        lBar.addView(item, params);
        item.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                responseForTestTool();
            }
        });

    }

    protected void loadBottomBar() {

        LinearLayout lBar = (LinearLayout) findViewById(R.id.layout_guide);
        lBar.setBackgroundResource(R.drawable.bg_bottom);
        lBar.removeAllViews();

        CreateBottomCountry();
        // CreateBottomCityTop();
        // CreateBottomSubscrible();
        CreateBottomTestTool();
    }

    @Override
    protected void onStart() {

        proBar.setFocusable(true);

        proBar.setFocusableInTouchMode(true);

        proBar.requestFocus();

        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (NetworkTestApp.isStop_celldb) {
            // 停止小区插入数据库
            SetUtil.stopImportVillageInfo(this);
            upCellDBView.hide();
        }
        if (NetworkTestApp.isBackRun_celldb) {
            // 插入小区数据库后台运行
            upCellDBView.hide();
        }
    }

    protected void setBackGround(int resid) {
        getWindow().setBackgroundDrawableResource(resid);
    }

    protected void setBackGround(Drawable bg) {
        getWindow().setBackgroundDrawable(bg);
    }

    protected void initTopBar() {

        if (getParent() != null) {
            removeLeftButton();
            return;
        }

        addGoBackButton();
    }

    protected void addGoBackButton() {
        setCloseButton(R.string.top_back, new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                goBack();

            }
        });
    }

    protected void addRightCloseButton() {
        setRightButton(R.string.top_close, new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                goBack();

            }
        });
    }

    protected void addShareButton() {
        setRightIconButton(R.drawable.btn_selector_share_bg, new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.setType("text/plain");
                intent.putExtra(Intent.EXTRA_SUBJECT, "suject");
                intent.putExtra(Intent.EXTRA_TEXT, "I would like to share this with you...");
                startActivity(Intent.createChooser(intent, getTitle()));
            }
        });
    }

    public void setContentView(int resid) {
        this.setContentView(View.inflate(getApplicationContext(), resid, null));
    }

    @Override
    public void setContentView(View view) {

        FrameLayout layout = (FrameLayout) findViewById(R.id.layout_content);
        layout.removeAllViews();
        layout.addView(view);
    }

    public void removeContentView() {
        FrameLayout layout = (FrameLayout) findViewById(R.id.layout_content);
        layout.removeAllViews();
    }

    @Override
    public void setTitle(CharSequence title) {
        TextView tv = (TextView) findViewById(R.id.title);
        tv.setText(title);
    }

    protected void setCloseButton(int resid, View.OnClickListener listener) {
        Button v = (Button) findViewById(R.id.btn_left);
        Drawable drawable = getResources().getDrawable(R.drawable.btn_selector_left_bg);
        v.setBackgroundDrawable(drawable);
        v.setVisibility(View.VISIBLE);
        v.setOnClickListener(listener);
        v.setText(resid);
    }

    protected void removeLeftButton() {
        ImageView v = (ImageView) findViewById(R.id.btn_left);
        v.setImageBitmap(null);
    }

    protected void setTitleBg(int resid) {
        RelativeLayout layout = (RelativeLayout) findViewById(R.id.layout_top);
        layout.setBackgroundResource(resid);
    }

    protected void setRightButton(int resid, View.OnClickListener listener) {
        Button v = (Button) findViewById(R.id.btn_right);
        Drawable drawable = getResources().getDrawable(R.drawable.btn_selector_left_bg);
        v.setBackgroundDrawable(drawable);
        v.setOnClickListener(listener);
        v.setVisibility(View.VISIBLE);
        v.setText(resid);
    }

    protected void setRightIconButton(int resid, View.OnClickListener listener) {
        Button v = (Button) findViewById(R.id.btn_right);
        Drawable drawable = getResources().getDrawable(resid);
        v.setBackgroundDrawable(drawable);
        v.setVisibility(View.VISIBLE);
        v.setOnClickListener(listener);
    }

    protected void setShareButton(View.OnClickListener listener) {
        Button v = (Button) findViewById(R.id.btn_right);
        Drawable drawable = getResources().getDrawable(R.drawable.btn_selector_share_bg);
        v.setBackgroundDrawable(drawable);
        v.setVisibility(View.VISIBLE);
        v.setOnClickListener(listener);
    }

    protected void startProBar() {

        proBar.setVisibility(View.VISIBLE);

    }

    protected void stopProBar() {

        proBar.setVisibility(View.GONE);

    }

    protected boolean onGoBack() {
        return false;
    }

    protected boolean goBack() {
        if (getParent() == null) {

            if (!onGoBack()) {
                exit();
            }
            return true;

        } else {

            return onGoBack();

        }

    }

    private void exit() {
        this.finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                System.out.println("go back----->" + this.getClass().getName());
                if (upCellDBView.isShown()) {
                    SetUtil.stopImportVillageInfo(this);
                    upCellDBView.setVisibility(View.GONE);
                    return false;
                } else if (menuView.isShown()) {
                    menuView.hide();
                    return false;
                } else {
                    return goBack();
                }
            case KeyEvent.KEYCODE_MENU:
                if (menuView.isShown()) {
                    menuView.hide();
                } else {
                    menuView.show();
                }
                break;
            default:
                break;
        }

        return false;
    }

    /**
     * 网络变化。
     * 
     * @param isConnect
     */
    protected void refreshByNetworkChange(boolean isConnect) {

    }

    /**
     * 定位成功。
     * 
     * @param intent
     */
    protected void locationSuccess(Intent intent) {

    }

    class LocationAndNetReceiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            if (intent == null) {
                return;
            }
            String action = intent.getAction();
            if (action.equals(LocationConstant.ACTION_LOCATION_BROADCASE)) {
                locationSuccess(intent);
            } else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                // 如果网络有变化。
                boolean noConnectivity = intent.getBooleanExtra(
                        ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
                refreshByNetworkChange(!noConnectivity);
            }

        }
    }

    /**
     * 各个继承类进行刷新操作。
     */
    public void refresh() {

    }

    /**
     * 监听应用退出广播
     * 
     * @author meizhen.xu
     */
    class APPExitReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(MyCommonConstant.PrivateActionName.APP_EXIT_FINISH)) {
                finish();
            }
        }
    }

}
